#!/bin/bash

# Check for correct number of arguments
if [ "$#" -ne 6 ]; then
    echo "Usage: $0 $(realpath ./模板目录/00.目录.docx) $grad_material_dir \"学号 姓名:2020240389 肖开科\" \"XX:大数据\" \"202X:2024\" \"XXX:网络空间安全\""
    exit 1
fi

TMPL_DOCX_FILE="$1"
grad_material_dir="$2"
shift
shift


TEMP_DIR="/tmp/docx_temp_$$" # Unique temporary directory

# Create a temporary directory and unzip the docx file
mkdir -p "$TEMP_DIR"
unzip -q "$TMPL_DOCX_FILE" -d "$TEMP_DIR"

# TODO: loop
for arg in "$@"; do
    FIND_STRING=${arg%%:*}
    REPLACE_STRING=${arg#*:}
    # Perform find and replace in document.xml
    # The 'g' flag ensures all occurrences are replaced on each line
    sed -i "s/${FIND_STRING}/${REPLACE_STRING}/g" "$TEMP_DIR/word/document.xml"
done

# Re-zip the modified content into a new docx file
# Ensure to change directory into the temp directory before zipping
output_filename=$(basename $TMPL_DOCX_FILE)
output_docx_fullpath="${grad_material_dir}/${output_filename}"

(cd "$TEMP_DIR" && zip -qr "$output_docx_fullpath" .)
# Clean up the temporary directory
rm -rf "$TEMP_DIR"

echo -e "Find and replace completed for '$TMPL_DOCX_FILE'. \nOutput file is at ${output_docx_fullpath}"